use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime};
use tokio::sync::RwLock;
use anyhow::Result;

/// 性能指标
#[derive(Debug, Clone)]
pub struct PerformanceMetrics {
    // 连接指标
    pub active_connections: u32,
    pub total_connections: u64,
    pub connection_rate: f64, // 连接/秒
    
    // 传输指标
    pub bytes_transferred: u64,
    pub transfer_rate: f64, // 字节/秒
    pub active_transfers: u32,
    pub completed_transfers: u64,
    pub failed_transfers: u64,
    
    // 响应时间指标
    pub average_response_time: Duration,
    pub max_response_time: Duration,
    pub min_response_time: Duration,
    
    // 系统资源指标
    pub cpu_usage: f64, // CPU使用率百分比
    pub memory_usage: u64, // 内存使用字节
    pub disk_io_rate: f64, // 磁盘IO速率
    
    // 缓存指标
    pub cache_hits: u64,
    pub cache_misses: u64,
    pub cache_hit_rate: f64,
    
    // 时间戳
    pub timestamp: SystemTime,
}

impl Default for PerformanceMetrics {
    fn default() -> Self {
        Self {
            active_connections: 0,
            total_connections: 0,
            connection_rate: 0.0,
            bytes_transferred: 0,
            transfer_rate: 0.0,
            active_transfers: 0,
            completed_transfers: 0,
            failed_transfers: 0,
            average_response_time: Duration::from_millis(0),
            max_response_time: Duration::from_millis(0),
            min_response_time: Duration::from_millis(0),
            cpu_usage: 0.0,
            memory_usage: 0,
            disk_io_rate: 0.0,
            cache_hits: 0,
            cache_misses: 0,
            cache_hit_rate: 0.0,
            timestamp: SystemTime::now(),
        }
    }
}

/// 性能监控器
pub struct PerformanceMonitor {
    metrics: Arc<RwLock<PerformanceMetrics>>,
    connection_times: Arc<RwLock<Vec<Instant>>>,
    response_times: Arc<RwLock<Vec<Duration>>>,
    transfer_history: Arc<RwLock<Vec<(Instant, u64)>>>, // (时间, 字节数)
    start_time: Instant,
    last_update: Instant,
}

impl PerformanceMonitor {
    pub fn new() -> Self {
        Self {
            metrics: Arc::new(RwLock::new(PerformanceMetrics::default())),
            connection_times: Arc::new(RwLock::new(Vec::new())),
            response_times: Arc::new(RwLock::new(Vec::new())),
            transfer_history: Arc::new(RwLock::new(Vec::new())),
            start_time: Instant::now(),
            last_update: Instant::now(),
        }
    }
    
    /// 记录新连接
    pub async fn record_connection(&self) {
        let mut metrics = self.metrics.write().await;
        metrics.active_connections += 1;
        metrics.total_connections += 1;
        
        let mut connection_times = self.connection_times.write().await;
        connection_times.push(Instant::now());
        
        // 保持最近1000个连接时间记录
        if connection_times.len() > 1000 {
            connection_times.remove(0);
        }
    }
    
    /// 记录连接断开
    pub async fn record_disconnection(&self) {
        let mut metrics = self.metrics.write().await;
        if metrics.active_connections > 0 {
            metrics.active_connections -= 1;
        }
    }
    
    /// 记录传输数据
    pub async fn record_transfer(&self, bytes: u64, success: bool) {
        let mut metrics = self.metrics.write().await;
        metrics.bytes_transferred += bytes;
        
        if success {
            metrics.completed_transfers += 1;
        } else {
            metrics.failed_transfers += 1;
        }
        
        let mut transfer_history = self.transfer_history.write().await;
        transfer_history.push((Instant::now(), bytes));
        
        // 保持最近1000个传输记录
        if transfer_history.len() > 1000 {
            transfer_history.remove(0);
        }
    }
    
    /// 记录响应时间
    pub async fn record_response_time(&self, duration: Duration) {
        let mut response_times = self.response_times.write().await;
        response_times.push(duration);
        
        // 保持最近1000个响应时间记录
        if response_times.len() > 1000 {
            response_times.remove(0);
        }
        
        // 更新统计
        let mut metrics = self.metrics.write().await;
        if response_times.len() == 1 {
            metrics.min_response_time = duration;
            metrics.max_response_time = duration;
        } else {
            if duration < metrics.min_response_time {
                metrics.min_response_time = duration;
            }
            if duration > metrics.max_response_time {
                metrics.max_response_time = duration;
            }
        }
    }
    
    /// 记录缓存命中
    pub async fn record_cache_hit(&self) {
        let mut metrics = self.metrics.write().await;
        metrics.cache_hits += 1;
    }
    
    /// 记录缓存未命中
    pub async fn record_cache_miss(&self) {
        let mut metrics = self.metrics.write().await;
        metrics.cache_misses += 1;
    }
    
    /// 更新系统资源使用情况
    pub async fn update_system_resources(&self, cpu_usage: f64, memory_usage: u64, disk_io_rate: f64) {
        let mut metrics = self.metrics.write().await;
        metrics.cpu_usage = cpu_usage;
        metrics.memory_usage = memory_usage;
        metrics.disk_io_rate = disk_io_rate;
    }
    
    /// 获取当前指标
    pub async fn get_metrics(&self) -> PerformanceMetrics {
        self.update_metrics().await;
        self.metrics.read().await.clone()
    }
    
    /// 更新计算指标
    async fn update_metrics(&self) {
        let now = Instant::now();
        let elapsed = now.duration_since(self.last_update);
        
        if elapsed < Duration::from_secs(1) {
            return; // 每秒最多更新一次
        }
        
        let mut metrics = self.metrics.write().await;
        
        // 计算连接速率
        {
            let connection_times = self.connection_times.read().await;
            let recent_connections = connection_times.iter()
                .filter(|&&time| now.duration_since(time) < Duration::from_secs(60))
                .count();
            metrics.connection_rate = recent_connections as f64 / 60.0;
        }
        
        // 计算传输速率
        {
            let transfer_history = self.transfer_history.read().await;
            let recent_transfers: u64 = transfer_history.iter()
                .filter(|(time, _)| now.duration_since(*time) < Duration::from_secs(60))
                .map(|(_, bytes)| bytes)
                .sum();
            metrics.transfer_rate = recent_transfers as f64 / 60.0;
        }
        
        // 计算平均响应时间
        {
            let response_times = self.response_times.read().await;
            if !response_times.is_empty() {
                let total: Duration = response_times.iter().sum();
                metrics.average_response_time = total / response_times.len() as u32;
            }
        }
        
        // 计算缓存命中率
        let total_cache_requests = metrics.cache_hits + metrics.cache_misses;
        if total_cache_requests > 0 {
            metrics.cache_hit_rate = metrics.cache_hits as f64 / total_cache_requests as f64;
        }
        
        metrics.timestamp = SystemTime::now();
        self.last_update = now;
    }
    
    /// 获取性能报告
    pub async fn get_performance_report(&self) -> PerformanceReport {
        let metrics = self.get_metrics().await;
        let uptime = self.start_time.elapsed();
        
        PerformanceReport {
            uptime,
            metrics,
            recommendations: self.generate_recommendations(&metrics).await,
        }
    }
    
    /// 生成性能优化建议
    async fn generate_recommendations(&self, metrics: &PerformanceMetrics) -> Vec<String> {
        let mut recommendations = Vec::new();
        
        // 连接相关建议
        if metrics.connection_rate > 100.0 {
            recommendations.push("连接速率过高，考虑增加连接池大小或负载均衡".to_string());
        }
        
        if metrics.active_connections > 500 {
            recommendations.push("活跃连接数过多，考虑优化连接管理或增加服务器资源".to_string());
        }
        
        // 传输相关建议
        if metrics.transfer_rate < 1024.0 * 1024.0 { // 小于1MB/s
            recommendations.push("传输速率较低，检查网络带宽或启用压缩".to_string());
        }
        
        if metrics.failed_transfers > metrics.completed_transfers / 10 {
            recommendations.push("传输失败率过高，检查网络稳定性和服务器资源".to_string());
        }
        
        // 响应时间建议
        if metrics.average_response_time > Duration::from_millis(1000) {
            recommendations.push("平均响应时间过长，考虑优化数据库查询或增加缓存".to_string());
        }
        
        // 缓存建议
        if metrics.cache_hit_rate < 0.7 {
            recommendations.push("缓存命中率较低，考虑增加缓存大小或优化缓存策略".to_string());
        }
        
        // 系统资源建议
        if metrics.cpu_usage > 80.0 {
            recommendations.push("CPU使用率过高，考虑优化算法或增加CPU资源".to_string());
        }
        
        if metrics.memory_usage > 1024 * 1024 * 1024 { // 大于1GB
            recommendations.push("内存使用量较大，考虑优化内存使用或增加内存".to_string());
        }
        
        recommendations
    }
    
    /// 重置所有指标
    pub async fn reset(&self) {
        let mut metrics = self.metrics.write().await;
        *metrics = PerformanceMetrics::default();
        
        self.connection_times.write().await.clear();
        self.response_times.write().await.clear();
        self.transfer_history.write().await.clear();
    }
}

/// 性能报告
#[derive(Debug, Clone)]
pub struct PerformanceReport {
    pub uptime: Duration,
    pub metrics: PerformanceMetrics,
    pub recommendations: Vec<String>,
}

impl PerformanceReport {
    /// 格式化报告为字符串
    pub fn format(&self) -> String {
        format!(
            "FTP服务器性能报告\n\
            =================\n\
            运行时间: {:.2} 小时\n\
            \n\
            连接统计:\n\
            - 活跃连接: {}\n\
            - 总连接数: {}\n\
            - 连接速率: {:.2} 连接/秒\n\
            \n\
            传输统计:\n\
            - 传输字节数: {} bytes ({:.2} MB)\n\
            - 传输速率: {:.2} bytes/s ({:.2} MB/s)\n\
            - 活跃传输: {}\n\
            - 完成传输: {}\n\
            - 失败传输: {}\n\
            \n\
            响应时间:\n\
            - 平均响应时间: {:.2} ms\n\
            - 最大响应时间: {:.2} ms\n\
            - 最小响应时间: {:.2} ms\n\
            \n\
            系统资源:\n\
            - CPU使用率: {:.2}%\n\
            - 内存使用: {} bytes ({:.2} MB)\n\
            - 磁盘IO速率: {:.2} bytes/s\n\
            \n\
            缓存统计:\n\
            - 缓存命中: {}\n\
            - 缓存未命中: {}\n\
            - 命中率: {:.2}%\n\
            \n\
            优化建议:\n\
            {}\n\
            \n\
            报告生成时间: {:?}",
            self.uptime.as_secs_f64() / 3600.0,
            self.metrics.active_connections,
            self.metrics.total_connections,
            self.metrics.connection_rate,
            self.metrics.bytes_transferred,
            self.metrics.bytes_transferred as f64 / (1024.0 * 1024.0),
            self.metrics.transfer_rate,
            self.metrics.transfer_rate / (1024.0 * 1024.0),
            self.metrics.active_transfers,
            self.metrics.completed_transfers,
            self.metrics.failed_transfers,
            self.metrics.average_response_time.as_millis(),
            self.metrics.max_response_time.as_millis(),
            self.metrics.min_response_time.as_millis(),
            self.metrics.cpu_usage,
            self.metrics.memory_usage,
            self.metrics.memory_usage as f64 / (1024.0 * 1024.0),
            self.metrics.disk_io_rate,
            self.metrics.cache_hits,
            self.metrics.cache_misses,
            self.metrics.cache_hit_rate * 100.0,
            if self.recommendations.is_empty() {
                "无特殊建议".to_string()
            } else {
                self.recommendations.join("\n- ")
            },
            self.metrics.timestamp
        )
    }
}

impl Default for PerformanceMonitor {
    fn default() -> Self {
        Self::new()
    }
}
